package boundary;

import gstd.Dice;
import desktop_resources.GUI;

public class DiceAnimation {
	int x1, x2, y1, y2;
	long time;
	final int MAX_TIME_MILLIS = 300; // approximately how long time the animation is allowed to last
	private Thread loop; // a thread used to be able to execute functionality in timed intervals

	public DiceAnimation(final Dice[] dices) {
		setLoop(new Thread() {
			public void run() {
				diceAnimationLoop(); // starts the animation
			}

			private void diceAnimationLoop() {
				while (true)
					try {
						// stores the current time to record how much time has paste when the loop has executed once
						long lastTime = System.nanoTime();
						Thread.sleep(60);
						
						// creates new dices using the 'real' dices, this is to get the correct number of sides
						Dice d1 = new Dice(dices[0].getSides());
						Dice d2 = new Dice(dices[1].getSides());
						d1.generateDice();
						d2.generateDice();
						int v1 = d1.getValue();
						int v2 = d2.getValue();
						
						// update the dice in the GUI
						GUI.setDice(v1, x1, y1, v2, x2, y2);
						long currentTime = System.nanoTime();

						// calculate in millisec how long time has paste since the loop begun sums it up
						time += currentTime - lastTime;
						int timeMilli = (int) (time / 1000000);

						// if the total time sumed up each interval is larger than MAX_TIME_MILLIS the animation is done
						if (timeMilli > MAX_TIME_MILLIS)
							return;
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
			}
		});
	}

	public void setPositions(int x1, int x2, int y1, int y2) {
		this.x1 = x1;
		this.x2 = x2;
		this.y1 = y1;
		this.y2 = y2;
	}

	public Thread getLoop() {
		return loop;
	}

	public void setLoop(Thread loop) {
		this.loop = loop;
	}

}
